package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"quiz-master/cache"
	"quiz-master/model"
	"strconv"
	"time"
)

func GoodOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	/*
	   SELECT
	   good_orders.id as OrderId,
	   goods.good_code as GoodCode,
	   goods.good_name as GoodName,
	   good_orders.order_code as  OrderCode,
	   good_orders.order_price as OrderPrice
	   FROM good_orders
	   LEFT JOIN goods ON good_orders.gid=goods.id
	*/
	var list []model.GoodOrderList
	redis_key := "redis_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("good_orders").
			Select(
				"good_orders.id as OrderId",
				"goods.good_code as GoodCode",
				"goods.good_name as GoodName",
				"good_orders.order_code as  OrderCode",
				"good_orders.order_price as OrderPrice",
			).Joins("LEFT JOIN goods ON good_orders.gid=goods.id").
			Offset(offset).Limit(size).Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	var count int64
	model.DB.Model(&model.GoodOrder{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  list,
		"count": count,
	})
	return
}

func GoodOrderDetail(c *gin.Context) {
	id := c.Query("id")
	var list model.GoodOrderList
	redis_key := "redis_detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("good_orders").
			Select(
				"good_orders.id as OrderId",
				"goods.good_code as GoodCode",
				"goods.good_name as GoodName",
				"good_orders.order_code as  OrderCode",
				"good_orders.order_price as OrderPrice",
			).Joins("LEFT JOIN goods ON good_orders.gid=goods.id").
			Where("good_orders.id = ?", id).Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})
	return
}
